﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace Susam
{
    public delegate void BackgroundScanStartedHandler();
    public delegate void BackgroundScanEndedHandler();

    public class BackgorundScanner : System.ComponentModel.BackgroundWorker
    {
        private static BackgorundScanner instance;
        private BackgorundScanner()
        {
            this.DoWork += new System.ComponentModel.DoWorkEventHandler(this.StartRescan);
        }

        public BackgroundScanStartedHandler BackgroundScanStarted;
        public BackgroundScanEndedHandler BackgroundScanEnded;

        private void StartRescan(object sender, DoWorkEventArgs e)
        {
            ConfigurationOptions options = e.Argument as ConfigurationOptions;
            List<ManualResetEvent> doneEvents = new List<ManualResetEvent>();

            foreach (var path in options.pathList)
            {
                if (!Directory.Exists(path))
                {
                    String errorMsg = path + " is not a valid directory path!";
                    MessageBox.Show(errorMsg, "Invalid Directory Path",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation);
                }
                else
                {
                    // Start scan
                    if (BackgroundScanStarted != null)
                    {
                        BackgroundScanStarted();
                    }

                    var factory = new FileScannerFactory();
                    foreach (var scanner in factory.GetScannerList(options.fileOptions))
                    {
                        ManualResetEvent doneEvent = new ManualResetEvent(false);
                        doneEvents.Add(doneEvent);
                        scanner.Scan(path, doneEvent);
                    }

                    // This is the place to wait for all threads to finish
                    WaitHandle.WaitAll(doneEvents.ToArray());
                    if (BackgroundScanEnded != null)
                    {
                        BackgroundScanEnded();
                    }
                }
            }

        }

        public static BackgorundScanner Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new BackgorundScanner();
                }
                return instance;
            }
        }
    }
}
